package ru.neoflex.datatable;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import ru.neoflex.dataobject.DataObjectDescriptor;
import ru.neoflex.dataobject.DataObjectProperty;

public class NeoTableModel extends AbstractTableModel {
	
	private final DataRowsAdapter adapter;
	private final DataObjectDescriptor descriptor;
	
	public NeoTableModel(DataObjectDescriptor descriptor, DataRowsAdapter adapter) {
		this.adapter = adapter;
		this.descriptor = descriptor;
	}
	
	//
	//	TableModel implementation
	//
	
	@Override
	public int getColumnCount() {
		return descriptor.getProperties().size();
	}

	@Override
	public int getRowCount() {
		return adapter.getItemsCount();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {		
		String propertyName = descriptor.getProperties().get(columnIndex).getName();
		Object value = adapter.getItems().get(rowIndex).get(propertyName);
		return value;
	}

	@Override
	public int findColumn(String arg0) {
		for (int i = 0; i < descriptor.getProperties().size(); i++) {
			DataObjectProperty property = descriptor.getProperties().get(i);
			if (property.getName().equals(arg0)) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public Class<?> getColumnClass(int arg0) {
		return descriptor.getProperties().get(arg0).getType();
	}

	@Override
	public String getColumnName(int arg0) {
		return descriptor.getProperties().get(arg0).getName();		
	}

	@Override
	public boolean isCellEditable(int arg0, int arg1) {
		return !descriptor.getProperties().get(arg1).isReadOnly();
	}

	@Override
	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		String propertyName = descriptor.getProperties().get(columnIndex).getName();
		adapter.getItems().get(rowIndex).set(propertyName, value);		
	}

	//
	//	end of TableModel implementation
	//
}
